package com.docparser.processor;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * 处理根号元素。
 */
public class RadicalProcessor extends BaseProcessor {
    /**
     * 处理根号元素。
     */
    public static void process(Element radElement, StringBuilder formula, ProcessorCallback callback) {
        if (radElement == null) return;
        
        String degree = getDegree(radElement, callback);
        String radicand = getRadicand(radElement, callback);
        
        appendRadical(formula, degree, radicand);
    }

    /**
     * 获取根号的次数。
     */
    private static String getDegree(Element radElement, ProcessorCallback callback) {
        StringBuilder degree = new StringBuilder();
        NodeList children = radElement.getElementsByTagNameNS(
            MATH_NAMESPACE, "deg");
        if (children.getLength() > 0) {
            callback.processElement((Element) children.item(0), degree);
            return degree.toString().trim();
        }
        return "";
    }

    /**
     * 获取根号内的表达式。
     */
    private static String getRadicand(Element radElement, ProcessorCallback callback) {
        StringBuilder content = new StringBuilder();
        NodeList children = radElement.getElementsByTagNameNS(
            MATH_NAMESPACE, "e");
        if (children.getLength() > 0) {
            callback.processElement((Element) children.item(0), content);
            return content.toString().trim();
        }
        return "";
    }

    /**
     * 添加根号表达式到LaTeX公式。
     */
    private static void appendRadical(StringBuilder formula, String degree, String radicand) {
        // 处理可能的特殊字符
        String cleanRadicand = radicand
            .replace("−", "-")  // 统一负号
            .trim();
            
        // 处理可能的上标
        cleanRadicand = cleanRadicand.replaceAll("\\^(\\{[^}]*\\}|[0-9])", "^$1");
        
        if (!degree.isEmpty()) {
            formula.append("\\sqrt[").append(degree).append("]{")
                  .append(cleanRadicand).append("}");
        } else {
            formula.append("\\sqrt{").append(cleanRadicand).append("}");
        }
    }
}
